'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';

interface MediaFile {
  id: string;
  name: string;
  originalName: string;
  type: 'image' | 'video' | 'document';
  size: number;
  url: string;
  uploadDate: string;
  category?: string;
}

interface MediaSelectorProps {
  isOpen: boolean;
  onClose: () => void;
  onSelect: (files: string[]) => void;
  multiple?: boolean;
  selectedFiles?: string[];
  title?: string;
}

export default function MediaSelector({
  isOpen,
  onClose,
  onSelect,
  multiple = false,
  selectedFiles = [],
  title = '选择媒体文件'
}: MediaSelectorProps) {
  const [mediaFiles, setMediaFiles] = useState<MediaFile[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<'all' | 'image' | 'video' | 'document'>('image');
  const [searchTerm, setSearchTerm] = useState('');
  const [selected, setSelected] = useState<string[]>([]);

  // Simple useEffect that only depends on isOpen
  useEffect(() => {
    if (isOpen) {
      fetchMediaFiles();
      // Reset selection each time modal opens
      setSelected([]);
    }
  }, [isOpen]);

  const fetchMediaFiles = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/admin/media');
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setMediaFiles(data.data);
        }
      }
    } catch (error) {
      console.error('Error fetching media files:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleFileSelect = (fileUrl: string) => {
    if (multiple) {
      if (selected.includes(fileUrl)) {
        setSelected(selected.filter(f => f !== fileUrl));
      } else {
        setSelected([...selected, fileUrl]);
      }
    } else {
      setSelected([fileUrl]);
    }
  };

  const handleConfirm = () => {
    onSelect(selected);
    onClose();
  };

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    const formData = new FormData();
    Array.from(files).forEach(file => {
      formData.append('files', file);
    });

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      });
      
      if (response.ok) {
        await fetchMediaFiles();
      }
    } catch (error) {
      console.error('Error uploading files:', error);
    }

    e.target.value = '';
  };

  const filteredFiles = mediaFiles.filter(file => {
    const matchesType = filterType === 'all' || file.type === filterType;
    const matchesSearch = file.originalName.toLowerCase().includes(searchTerm.toLowerCase());
    return matchesType && matchesSearch;
  });

  if (!isOpen) return null;

  return (
    <div 
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-[60]"
      style={{ animation: isOpen ? 'fadeIn 0.2s ease-out' : 'none' }}>
      <div className="bg-white rounded-lg w-full max-w-4xl max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b">
          <h2 className="text-xl font-bold">{title}</h2>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 text-2xl"
          >
            ×
          </button>
        </div>

        {/* Controls */}
        <div className="p-4 border-b bg-gray-50">
          <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
            <div className="flex flex-col md:flex-row gap-4 items-start md:items-center">
              {/* Upload */}
              <label className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors cursor-pointer text-sm">
                📁 上传文件
                <input
                  type="file"
                  multiple
                  accept="image/*,video/*,.pdf,.doc,.docx"
                  onChange={handleUpload}
                  className="hidden"
                />
              </label>

              {/* Search */}
              <input
                type="text"
                placeholder="搜索文件..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="border border-gray-300 rounded-lg px-3 py-2 w-48 text-sm"
              />

              {/* Filter */}
              <select
                value={filterType}
                onChange={(e) => setFilterType(e.target.value as any)}
                className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
              >
                <option value="all">所有类型</option>
                <option value="image">🖼️ 图片</option>
                <option value="video">🎥 视频</option>
                <option value="document">📄 文档</option>
              </select>
            </div>

            {/* Selected count */}
            {multiple && selected.length > 0 && (
              <span className="text-sm text-gray-600">
                已选择 {selected.length} 个文件
              </span>
            )}
          </div>
        </div>

        {/* File Grid */}
        <div className="flex-1 overflow-auto p-4">
          {loading ? (
            <div className="flex items-center justify-center h-40">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
              <span className="ml-3 text-gray-600">加载中...</span>
            </div>
          ) : filteredFiles.length === 0 ? (
            <div className="flex items-center justify-center h-40 text-gray-500">
              没有找到媒体文件
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
              {filteredFiles.map((file) => (
                <div
                  key={file.id}
                  onClick={() => handleFileSelect(file.url)}
                  className={`
                    relative border rounded-lg overflow-hidden cursor-pointer transition-all
                    ${selected.includes(file.url) 
                      ? 'border-blue-500 bg-blue-50 ring-2 ring-blue-200' 
                      : 'border-gray-200 hover:border-gray-300 hover:shadow-md'
                    }
                  `}
                >
                  <div className="aspect-square bg-gray-100 flex items-center justify-center">
                    {file.type === 'image' ? (
                      <Image
                        src={file.url}
                        alt={file.originalName}
                        fill
                        className="object-cover"
                        onError={(e) => {
                          e.currentTarget.src = '';
                        }}
                      />
                    ) : (
                      <div className="text-3xl">
                        {file.type === 'video' ? '🎥' : '📄'}
                      </div>
                    )}
                  </div>
                  
                  {/* Selection indicator */}
                  {selected.includes(file.url) && (
                    <div className="absolute top-2 right-2 bg-blue-600 text-white w-6 h-6 rounded-full flex items-center justify-center text-sm">
                      ✓
                    </div>
                  )}
                  
                  <div className="p-2">
                    <div className="text-xs font-medium text-gray-900 truncate" title={file.originalName}>
                      {file.originalName}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-4 border-t bg-gray-50">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50"
          >
            取消
          </button>
          <button
            onClick={handleConfirm}
            disabled={selected.length === 0}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            确认选择 {selected.length > 0 && `(${selected.length})`}
          </button>
        </div>
      </div>
    </div>
  );
}